<template>
  <el-dialog title="排班" v-model="schedulingVisible" width="500px" destroy-on-close>
    <el-form
      :model="state.scheduFormData"
      ref="scheduForm"
      label-width="100px"
      :rules="rules"
      :inline="false"
    >
      <el-form-item label="接访日期" required prop="dateRange">
        <el-date-picker
          v-model="state.scheduFormData.dateRange"
          type="daterange"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD"
          :disabledDate="disabledDate"
        />
      </el-form-item>
      <el-form-item label="接访时间段" prop="timeRange">
        <el-checkbox-group v-model="state.scheduFormData.timeRange">
          <el-checkbox v-for="(time, index) in timeList" :key="index" :label="time">
            {{ time }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span>
        <el-button @click="schedulingVisible = false">取消</el-button>
        <el-button type="primary" @click="submitScheduling">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import moment from 'moment'
import * as ProsecutorgeneralmanagerApi from '@/api/pro/prosecutorgeneralmanager'
import { debounce } from 'lodash-es'

const props = defineProps({
  row: {
    type: Object,
    default: () => {}
  }
})

const message = useMessage()
const scheduForm = ref()
const rules = {
  dateRange: [{ required: true, message: '请选择接访日期', trigger: 'change' }],
  timeRange: [
    {
      required: true,
      message: '请选择接访时间段',
      trigger: 'change'
    }
  ]
}
const schedulingVisible = ref(false)
const timeList = ref(['9:00 ~ 10:30', '10:45 ~ 12:00', '14:00 ~ 15:30', '15:45 ~ 17:00'])
const disabledDates = ref([])
const disableList = ref([])
const state = reactive({
  scheduFormData: {
    dateRange: '',
    timeRange: []
  }
})
watch(
  () => schedulingVisible.value,
  (n) => {
    if (n) {
      getScheduList()
      state.scheduFormData = {
        dateRange: '',
        timeRange: []
      }
    }
  }
)

// 获取检察长排班信息
function getScheduList() {
  disabledDates.value.length = 0
  const params = {
    pageNo: 1,
    pageSize: 100,
    acceptUserId: props.row.id
  }
  ProsecutorgeneralmanagerApi.getScheduling(params).then((res) => {
    res.list.forEach((r) => {
      if (!disabledDates.value.includes(r.acceptTime)) {
        disabledDates.value.push(r.acceptTime)
      }
    })
  })
}

const submitScheduling = debounce(() => {
  scheduForm.value.validate((valid, fields) => {
    if (valid) {
      const startTime = state.scheduFormData.dateRange[0]
      const endTime = state.scheduFormData.dateRange[1]
      const data = {
        requestTime: state.scheduFormData.timeRange,
        acceptTime: getDatesInRange(startTime, endTime).join(','),
        acceptUserId: props.row.id
      }
      ProsecutorgeneralmanagerApi.scheduling(data).then(() => {
        schedulingVisible.value = false
        message.success('排班提交成功')
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}, 1000)

// 禁用日期
function disabledDate(time) {
  const day = time.getDay()
  // 禁用周六和周日（0 表示周日，6 表示周六）
  if (day === 0 || day === 6) {
    disableList.value.push(time)
    return true
  }
  // 禁用今天及之前
  if (time.getTime() < new Date().getTime()) {
    disableList.value.push(time)
    return true
  }
  // 禁用已排班
  if (disabledDates.value.includes(moment(time).format('YYYY-MM-DD'))) {
    disableList.value.push(time)
    return true
  }
  return false
}

// 根据时间范围获取每天的日期列表
function getDatesInRange(startDate, endDate) {
  const dates = []
  let currentDate = new Date(startDate)
  while (currentDate <= new Date(endDate)) {
    if (
      !isDateInArray(currentDate, disableList.value) &&
      currentDate.getDay() !== 0 &&
      currentDate.getDay() !== 6
    ) {
      dates.push(new Date(currentDate))
    }
    currentDate.setDate(currentDate.getDate() + 1)
  }
  return dates.map((date) => date.toISOString().split('T')[0])
}

// 判断当前勾选日期是否在禁用日期列表内
function isDateInArray(date, array) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1 // 月份从 0 开始，所以加 1
  const day = date.getDate()
  return array.some((item) => {
    const itemDate = new Date(item)
    return (
      itemDate.getFullYear() === year &&
      itemDate.getMonth() + 1 === month &&
      itemDate.getDate() === day
    )
  })
}

defineExpose({ schedulingVisible })
</script>

<style></style>
